﻿#include "udp_slave.h"
#include "msg_clientdata.h"

UDPSlave::UDPSlave()
{
	//    mType = 0;//Unicast
	//    mType = 1;//Broadcast
	mType = 2;//Multicast

   // InitSocket();

    //虚拟数据
    //  InitTimer();

}

void UDPSlave::InitSocket(QString serverIP, int port)
{
	mUdpSocket = new QUdpSocket;//初始化socket
	mGroupAddress.setAddress(serverIP);//设置组播地址
    mUdpSocket->bind(port);//绑定端口号
	if (mType == 2)
	{
        //组播的数据的生存期，数据报每跨1个路由就会减1.表示多播数据报只能在同一路由下的局域网内传播
		mUdpSocket->setSocketOption(QAbstractSocket::MulticastTtlOption, 1);
	}
}

void UDPSlave::InitTimer()
{
	mTimer = new QTimer;//初始化定时器
	connect(mTimer, &QTimer::timeout, this, [=]
		{
			SendData();
		});
	mTimer->start(100);//每隔一秒发送一次数据
}

void UDPSlave::SendData()
{
	Msg_ClientData msg;

	QByteArray _data = msg.ToByte();
	if (mType == 0)//单播
	{
		QHostAddress _peerHostAddress = QHostAddress("10.0.0.177");//对位服务器IP
		quint16 _port = 6666;//对位服务器端口
		if (-1 != mUdpSocket->writeDatagram(_data.data(), _data.size(), _peerHostAddress, _port))
		{
			qDebug() << "Unicast ==> Send data : " << _data << endl;
		}
		mUdpSocket->flush();
	}
	else if (mType == 1)//广播
	{
		quint16 _port = 6666;//广播端口
		if (-1 != mUdpSocket->writeDatagram(_data.data(), QHostAddress::Broadcast, _port))
		{
			qDebug() << "Broadcast ==> Send data : " << _data << endl;
		}
		mUdpSocket->flush();
	}
	else if (mType == 2)//组播
	{
		quint16 _port = 10020;//组播端口
		if (-1 != mUdpSocket->writeDatagram(_data.data(), _data.length(), mGroupAddress, _port))
		{
			qDebug() << "Multicast ==> Send data : " << _data << endl;
		}
		mUdpSocket->flush();
	}
	else
	{
		qDebug() << "mType is error! " << endl;
		return;
	}


}
